package com.spring.demo4.eg3;

import org.springframework.aop.ClassFilter;
import org.springframework.aop.MethodMatcher;
import org.springframework.aop.Pointcut;
import org.springframework.aop.framework.ProxyFactory;
import org.springframework.aop.support.DefaultPointcutAdvisor;

import java.lang.reflect.Method;

/**
 * @author vhans
 */
public class Test {
    /**
     * 模拟用户登录，密码错误则报错
     */
    @org.junit.Test
    public void test(){
        UserService userService = new UserService();
        Pointcut pointcut = new Pointcut() {
            @Override
            public ClassFilter getClassFilter() {
                return UserService.class::isAssignableFrom;
            }

            @Override
            public MethodMatcher getMethodMatcher() {
                return new MethodMatcher() {
                    @Override
                    public boolean matches(Method method, Class<?> targetClass) {
                        return "work".equals(method.getName());
                    }

                    @Override
                    public boolean isRuntime() {
                        return false;
                    }

                    @Override
                    public boolean matches(Method method, Class<?> targetClass, Object... args) {
                        return false;
                    }
                };
            }
        };

        DefaultPointcutAdvisor advisor = new DefaultPointcutAdvisor(pointcut, new RegisterThrowsAdvice());

        ProxyFactory proxyFactory = new ProxyFactory();
        proxyFactory.setTarget(userService);
        proxyFactory.addAdvisor(advisor);
        UserService proxy = (UserService) proxyFactory.getProxy();
        try {
            proxy.work("111");
        } catch (Exception ignored) {

        }
    }
}
